package tu.bianli.queue;

public class LinkQueue {
    private Node front;     //队首指针
    private Node rear;      //队尾指针

    //链队列的构造函数
    public LinkQueue(){
        front = rear = null;        //将队首指针和队尾指针都置空
    }

    //链队列构造完整链表
    public LinkQueue(Object[] temp){
        this();
        for (int i = 0; i < temp.length; i++) {
            offer(temp[i]);
        }
    }

    //队列置空
    public void clear(){
        front = rear = null;         //将队首指针和队尾指针都置空
    }

    //队列判空
    public boolean isEmpty(){
        return front == null;           //队首指针为空则空
    }

    //求队列长度
    public int length(){        
        Node p = front;             //将p指向队首指针指向的位置
        int length = 0;             //设置长度默认值为0
        while(p != null){       //若p指向位置不为空
            p = p.next;         //指针下移
            ++length;;          //计数器+1
        }
        return length;          //返回长度值
    }

    //取队首元素
    public Object peek(){
        if(!isEmpty())             //判空
            return front.data;      //返回首元素数据域、
        else
            return null;            //返回空
    }

    //入队
    public void offer(Object x){
        Node p = new Node(x);       //初始化新结点
        if(!isEmpty()){             //判空
            rear.next = p;          //连接新结点
            rear = rear.next;       //尾指针后移
            // rear = p;
        }else
            front = rear = p;       //首结点
    }

    //出队
    public Object poll(){
        if(!isEmpty()){             //判空
            Node p = front;         //新指针p指向队首指针指向的结点
            front = front.next;     //首结点后移
            if(p == rear)           //若p指向尾指针
                rear = null;        //则将尾指针指向结点（最后一个结点）出队
            return p.data;          //返回p指向结点的数据域
        }else   
            return null;            //返回空值
    }

    //输出队列
    public void display() throws Exception {
        if(!isEmpty()){
            Node p = front;         //新指针指向队首指针指向的结点
            while(p != null){
                System.out.print(p.data + " ");
                p = p.next;
            }
        }else{
            throw new Exception("此队列为空");
        }
    }
}
